package org.yray.sip.visit;



import org.yray.sip.base.MsgType;
import org.yray.sip.base.SipMsg;
import org.yray.sip.constant.SessionStatusEnum;
import org.yray.sip.creator.MessageCreator;
import org.yray.sip.factory.SipSessionFactory;
import org.yray.sip.factory.StopWatchFactory;
import org.yray.sip.rtp.receive.AbstractBeanHolder;
import org.yray.sip.rtp.sender.ISipSessionCache;
import org.yray.sip.server.SipServerContext;
import org.yray.sip.server.SipSession;
import org.yray.sip.utils.IcspBeanHolder;

import java.util.Optional;


public class Sip183Visitor extends AbstractBeanHolder implements ISipVisitor{

    @Override
    public void doALeg(SipMsg sipMsg, SipServerContext ssc) {
        log(sipMsg.getCallId(),"Sip183Visitor,doALeg");
        SipSession sipSession= IcspBeanHolder.getBean(ISipSessionCache.class).get(sipMsg.getCallId());
        //超时未应答，又发起183的情况
        if((System.currentTimeMillis()-sipSession.getBeginTime())>30000
                &&sipSession.getStatus().get()== SessionStatusEnum.CALL_ING)
        {
            String msg = MessageCreator.getCreator(MsgType.CANCEL).createMsg(sipSession);
            getSipServerHandler(sipSession.getCallId()).sendToSipServer(sipSession,msg);
            log(sipMsg.getCallId(),"超时未应答，又发起183的情况");
        }
        else {
            IcspBeanHolder.getBean(SipSessionFactory.class).resolvRtp(sipSession,sipMsg.getSdpList());
            IcspBeanHolder.getBean(ISipSessionCache.class).addRtcpIp(sipSession);
            IcspBeanHolder.getBean(ISipSessionCache.class).putRecvPort(sipSession.getSideRtcpIp() + sipSession.getSideRtpPort(), sipSession.getCallId());
            getRtcpSender().sendRR(ssc,sipSession.getCallId());
            sipSession.setSipMap(sipMsg.getSipMap());
        }
        getStopWatchFactory().periodStart(sipSession, StopWatchFactory.TASK_183_A);
        getEventFactory().sipEvent(sipMsg.getCallId(), sipMsg.getSipCode());
    }

    @Override
    public void doBLeg(SipMsg sipMsg, SipServerContext ssc) {
        log(sipMsg.getCallId(),"Sip183Visitor,doBLeg");
        //更新B的状态
        SipSession bSipSession=IcspBeanHolder.getBean(ISipSessionCache.class).get(sipMsg.getCallId());
        Optional.ofNullable(bSipSession).ifPresent((v)->{
            v.getStatus().set(SessionStatusEnum.TO_MAN_RING);
        });
        bSipSession.setSipMap(sipMsg.getSipMap());

        String aId=getIdRuleComponent().getAIdFromAOrBId(sipMsg.getCallId());
        SipSession aSipSession=IcspBeanHolder.getBean(ISipSessionCache.class).get(aId);
        Optional.ofNullable(aSipSession).ifPresent((v)->{
            v.getStatus().set(SessionStatusEnum.TO_MAN_RING);
        });
        getEventFactory().sipEvent(sipMsg.getCallId(), sipMsg.getSipCode());
    }
}
